<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('sysOplog.name')" prop="likeLogName">
              <el-input
                v-model="queryParams.likeLogName"
                :placeholder="$t('sysOplog.nameRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysOplog.level')" prop="logLevel">
              <el-input
                v-model="queryParams.logLevel"
                :placeholder="$t('sysOplog.levelRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysOplog.inform')" prop="likeLogMsg">
              <el-input
                v-model="queryParams.likeLogMsg"
                :placeholder="$t('sysOplog.informRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item :label="$t('sysOplog.time')" prop="partition">
              <el-date-picker
                v-model="partition"
                type="month"
                value-format="YYYY-MM"
                :placeholder="$t('sysOplog.monthRequired')"
                class="!w-[203px]"
                clearable
                @change="handleMonth"
              />
              <el-date-picker
                v-if="queryParams.partition"
                v-model="createTimeArr"
                class="dropdown-left"
                type="daterange"
                :start-placeholder="$t('sysOplog.startTimeReuired')"
                :end-placeholder="$t('sysOplog.endTimeRequired')"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                clearable
                @change="dateEvents"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="search-btn">
              <el-button type="primary" @click="tableHooks.handleQuery()">
                {{ $t("common.search") }}
              </el-button>
              <el-button @click="resetQuery">{{
                $t("common.reset")
              }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="clear"></div>
    </div>
    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <el-row justify="space-between">
          <el-col :span="17">
            <el-button
              v-hasPerm="['rbac:log:delete']"
              type="primary"
              @click="deleteRecords"
            >
              {{ $t("common.delete") }}
            </el-button>
          </el-col>
          <el-col :span="7" class="container-float">
            <el-button
              v-hasPerm="['rbac:log:export']"
              class="dropdown-left"
              type="primary"
              plain
              @click="tableHooks.handleExport(t('sysUserLog.name'))"
            >
              {{ $t("common.export") }}
            </el-button>
            <jmash-column-select
              v-model="tableLabel"
              label-name="rbac/rbac-log"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 表格开始 -->
      <jmash-table
        ref="multipleTableRef"
        row-key="logId"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @sort-change="handleSort"
      >
        <template #operator="scope">
          <span
            v-if="
              scope.data.row.createBy != '00000000-0000-0000-0000-000000000000'
            "
            >{{ rbacApi.userInfo(scope.data.row.createBy).realName }}</span
          >
        </template>
        <template #time="scope">
          <span>{{
            format(new Date(scope.data.row.createTime), "yyyy-MM-dd HH:mm:ss")
          }}</span>
        </template>
      </jmash-table>
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
      </template>
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="$t('sysOplog.choose')"
      width="500px"
      @close="resetYearForm"
    >
      <el-form ref="yearFormRef" :model="yearForm" :rules="yearFormRules">
        <el-form-item :label="$t('sysOplog.year')" prop="number">
          <el-select v-model="yearForm.number" clearable>
            <el-option :label="1 + $t('sysOplog.year')" :value="1" />
            <el-option :label="2 + $t('sysOplog.year')" :value="2" />
            <el-option :label="3 + $t('sysOplog.year')" :value="3" />
            <el-option :label="4 + $t('sysOplog.year')" :value="4" />
            <el-option :label="5 + $t('sysOplog.year')" :value="5" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetYearForm">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button type="primary" @click="submitForm">
            {{ $t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, getCurrentInstance } from "vue";
import {
  type TableColumn,
  type TableSort,
  type DialogRef,
  useTableHooks,
} from "jmash-core";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { format } from "date-fns";
import { rbacApi } from "@/api/system/rbac";
import type { FormInstance, FormRules } from "element-plus";
import { getDaysInMonth } from "@/utils/common";
import type { LogReq, YearForm } from "@/api/system/log/types";
import { logApi } from "@/api/system/log/index";
/**
 * 获取全局方法
 * getCurrentInstance()
 * 只能在setup或生命周期中使用，其他地方使用是无效的
 */
const { proxy } = getCurrentInstance() as any;
const queryParams = ref<LogReq>({
  curPage: 1,
  pageSize: 10,
  partition: getDaysInMonth()[0].split("-")[1],
});
let startDate = ref(
  (new Date(getDaysInMonth(getDaysInMonth()[0].substr(0, 7))[0]).getTime() -
    24 * 60 * 60 * 1000) as any,
);
let endDate = ref(
  new Date(getDaysInMonth(getDaysInMonth()[0].substr(0, 7))[1]) as any,
);
let createTimeArr = ref();
let partition = ref(getDaysInMonth()[0].substr(0, 7));
const tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "sysOplog.name",
    prop: "logName",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysOplog.level",
    prop: "logLevel",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysOplog.inform",
    prop: "logMsg",
    isColumn: true,
  },
  {
    label: "sysOplog.content",
    prop: "logContent",
    isColumn: true,
  },
  {
    label: "sysOplog.userIp",
    prop: "userIp",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysOplog.proxyIp",
    prop: "proxyIp",
    isColumn: true,
  },
  {
    label: "sysOplog.operator",
    prop: "createBy",
    slotName: "operator",
    columnType: "slot",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysOplog.time",
    prop: "createTime",
    slotName: "time",
    columnType: "slot",
    isColumn: true,
    sortable: true,
  },
]);
const dialog: DialogRef = reactive({
  title: "",
  visible: false,
});
const yearFormRef = ref<FormInstance>();
const yearForm: YearForm = reactive({
  number: 1,
});
const yearFormRules = reactive<FormRules<YearForm>>({
  number: [
    { required: true, message: t("sysOplog.yearRequired"), trigger: "change" },
  ],
});

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, logApi, queryParams);

// 重置
function resetQuery() {
  queryFormRef.value.resetFields();
  delete queryParams.value.startCreateTime;
  delete queryParams.value.endCreateTime;
  createTimeArr.value = [];
  partition.value = getDaysInMonth()[0].substr(0, 7);
  tableHooks.handleQuery();
}

function resetYearForm() {
  yearFormRef.value?.resetFields();
  dialog.visible = false;
}

// 批量删除
function deleteRecords() {
  ElMessageBox.confirm(t("sysOplog.confirmDelete"), t("common.delete"), {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => {
      dialog.visible = true;
    })
    .catch(() => {});
}

const submitForm = async () => {
  await yearFormRef.value?.validate((valid) => {
    if (valid) {
      logApi.batchDelLog(yearForm.number).then((response) => {
        if (response.status === 200) {
          ElMessage({
            message:
              t("common.successDelete") + response.data + t("common.stripData"),
            type: "success",
          });
          dialog.visible = false;
          tableHooks.handleQuery();
        }
      });
    } else {
      return Promise.reject();
    }
  });
};

// 根据月份查天数
function handleMonth(val: any) {
  queryParams.value.partition = val.split("-")[1];
  startDate.value = new Date(
    new Date(getDaysInMonth(val)[0]).getTime() - 24 * 60 * 60 * 1000,
  );
  endDate.value = new Date(getDaysInMonth(val)[1]);
}
const disabledDate = (time: Date) => {
  return time.getTime() < startDate.value || time.getTime() > endDate.value;
};
function dateEvents(value: Date[]) {
  queryParams.value.startCreateTime = proxy.$moment.formatDate(value[0]);
  queryParams.value.endCreateTime = proxy.$moment.formatDate(value[1]);
}

// 处理排序
function handleSort(sort: TableSort) {
  tableHooks.handleSort(sort.prop, sort.order);
}

tableHooks.getList();
</script>
